// store.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    cartItems: JSON.parse(localStorage.getItem('cart')) || []
  },
  mutations: {
    addToCart(state, product) {
      const existingItem = state.cartItems.find(item => 
        item.id === product.id && 
        item.colorId === product.colorId && 
        item.capacityId === product.capacityId
      )
      
      if (existingItem) {
        existingItem.quantity += product.quantity
      } else {
        state.cartItems.push({
          ...product,
          selected: true
        })
      }
      
      localStorage.setItem('cart', JSON.stringify(state.cartItems))
    },
	 // 更新商品数量
	    updateCartItemQuantity(state, payload) {
	      state.cartItems[payload.index].quantity = payload.quantity
	      localStorage.setItem('cart', JSON.stringify(state.cartItems))
	    },
	    
	    // 删除商品
	    removeCartItem(state, index) {
	      state.cartItems.splice(index, 1)
	      localStorage.setItem('cart', JSON.stringify(state.cartItems))
	    },
	    
	    // 清空购物车
	    clearCartItems(state) {
	      state.cartItems = []
	      localStorage.removeItem('cart')
	    },
		 // 全选/取消全选
		    selectAllCartItems(state, selected) {
		      state.cartItems.forEach(item => {
		        item.selected = selected
		      })
		      localStorage.setItem('cart', JSON.stringify(state.cartItems))
		    }
  
  }
})